package ar.uba.fi.RSACryptoFiuba.model.keygeneration;

import ar.uba.fi.RSACryptoFiuba.model.InvalidValueException;
import ar.uba.fi.RSACryptoFiuba.model.RSACalculator;
import ar.uba.fi.RSACryptoFiuba.model.RSAMessage;
import ar.uba.fi.RSACryptoFiuba.model.RSAStep;

public class CalculateNStep extends RSAStep {
	
	@Override
	public void execute(RSAMessage message) {
		RSAKeyGenerationMessage keyGenerationMessage = (RSAKeyGenerationMessage) message;
		Integer p = Integer.valueOf(keyGenerationMessage.getP());
		Integer q = Integer.valueOf(keyGenerationMessage.getQ());
		Integer n =  RSACalculator.multiply(p,q);
		keyGenerationMessage.setN(n.toString());
	}
	
	@Override
	public void undo(RSAMessage message) {
		RSAKeyGenerationMessage keyGenerationMessage = (RSAKeyGenerationMessage) message;
		keyGenerationMessage.setN("");
	}

	@Override
	public void test(RSAMessage message) {
		String element = message.getElementToEvaluate();
		verifyNumericalValue(element);
		RSAKeyGenerationMessage keyGenerationMessage = (RSAKeyGenerationMessage) message;
		Integer p = Integer.valueOf(keyGenerationMessage.getP());
		Integer q = Integer.valueOf(keyGenerationMessage.getQ());
		Integer n =  RSACalculator.multiply(p,q);
		boolean isValid = String.valueOf(n).equals(element);
		if(!isValid){
			throw new InvalidValueException("El número n debe ser igual a p*q.");
		}
		keyGenerationMessage.setN(element);
	}

}
